package com.wltjack.sysmanage.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.wltjack.sysmanage.common.datasource.DynamicDataSource;
import com.wltjack.sysmanage.common.enums.DataSourceTypeEnum;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName MybatisPlusConfig
 * @Description MybatisPlus配置
 * @Author kangliang
 * @Date 2021/03/01 10:47
 * @Version 1.0
 */
// 开启事务
//@EnableTransactionManagement
@Configuration
// // 扫描mapperdao的地址
@MapperScan(basePackages = "com.wltjack.**.mapper")
public class MybatisPlusConfig {

    /**
     * 功能描述: 分页插件
     *
     * @return: PaginationInterceptor
     * @Author: kangliang
     * @Date: 2021-03-01 10:49
     */
//    @Bean
//    @ConditionalOnMissingBean
//    public PaginationInterceptor paginationInterceptor() {
//        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
//        paginationInterceptor.setLimit(-1);
//        return paginationInterceptor;
//    }
    @Bean
    @ConditionalOnMissingBean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setLimit(-1);
        return paginationInterceptor;
    }


    /**
     * 功能描述: 自定义主键(雪花算法)
     *
     * @return: IdentifierGenerator
     * @Author: kangliang
     * @Date: 2021-03-01 10:49
     */
//    @Bean
//    public IdentifierGenerator idGenerator() {
//        return new DefaultIdentifierGenerator();
//    }
    @Bean(name = "db1")
    //与配置文件中的层次结构相同
    @ConfigurationProperties(prefix = "spring.datasource.druid.db1")
    public DataSource db1() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "db2")
    //与配置文件中的层次结构相同
    @ConfigurationProperties(prefix = "spring.datasource.druid.db2")
    public DataSource db2() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "multipleTransactionManager")
    @Primary
    public DataSourceTransactionManager multipleTransactionManager(@Qualifier("multipleDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 动态数据源配置
     */
    @Bean(name = "multipleDataSource")
    @Primary
    public DataSource multipleDataSource(@Qualifier("db1") DataSource db1,
                                         @Qualifier("db2") DataSource db2) {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceTypeEnum.DB1.getCode(), db1);
        targetDataSources.put(DataSourceTypeEnum.DB2.getCode(), db2);
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.setDefaultTargetDataSource(db1);
        return dynamicDataSource;
    }


    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        //导入mybatissqlsession配置
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        // 公共字段自动填充配置
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setMetaObjectHandler(new MyMetaObjectHandler());
        sqlSessionFactory.setGlobalConfig(globalConfig);
        //指明数据源
        sqlSessionFactory.setDataSource(multipleDataSource(db1(), db2()));

        //指明mapper.xml位置(配置文件中指明的xml位置会失效用此方式代替，具体原因未知)
//        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/**Mapper.xml"));
        //指明实体扫描(多个package用逗号或者分号分隔)
//        sqlSessionFactory.setTypeAliasesPackage("com.huaxi.sysmanage.demo1.entity");
        sqlSessionFactory.setTypeAliasesPackage("com.huaxi.**.entity");

        //导入mybatis配置
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(false);
        sqlSessionFactory.setConfiguration(configuration);
        //PerformanceInterceptor(),OptimisticLockerInterceptor()
        //添加分页功能
        sqlSessionFactory.setPlugins(new Interceptor[]{
                paginationInterceptor()
        });

        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resource = resolver.getResources("classpath*:/mappers/**/*.xml");
        sqlSessionFactory.setMapperLocations(resource);
//        //导入全局配置
//        sqlSessionFactory.setGlobalConfig(globalConfiguration());
        return sqlSessionFactory.getObject();
    }

//    /**
//     * 功能描述: 在代码中配置MybatisPlus替换掉application.yml中的配置
//     *
//     * @return: GlobalConfiguration
//     * @Author: kangliang
//     * @Date: 2021-03-01 16:59
//     */
//    @Bean
//    public GlobalConfiguration globalConfiguration() {
//        GlobalConfiguration conf = new GlobalConfiguration(new LogicSqlInjector());
//        conf.setLogicDeleteValue("-1");
//        conf.setLogicNotDeleteValue("1");
//        //主键类型 0:数据库ID自增, 1:用户输入ID,2:全局唯一ID (数字类型唯一ID), 3:全局唯一ID UUID
//        conf.setIdType(0);
//        //   conf.setMetaObjectHandler(new MyMetaObjectHandler());
//        //驼峰下划线转换含查询column及返回column(column下划线命名create_time，返回java实体是驼峰命名createTime，开启后自动转换否则保留原样)
//        conf.setDbColumnUnderline(true);
//        //是否动态刷新mapper
//        conf.setRefresh(true);
//        return conf;
//    }

}
